package service

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils"
	"EnjoyWorking/utils/storage"
	"errors"
)

type WprItem struct {}

func (service *WprItem) Insert(item *model.WprItem) error {
	//检验工作计划总结表是否存在
	var total int64
	if err := storage.MySqlDb().Model(&model.Wpr{}).Where("id = ?", item.ParentID).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_WPR_NOT_EXIST.String())
	}

	//检验项目是否存在
	if err := storage.MySqlDb().Model(&model.Project{}).Where("id = ?", item.ProjectID).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_PROJECT_NOT_EXIST.String())
	}

	//责任人是否存在
	if err := storage.MySqlDb().Model(&model.User{}).Where("id = ?", item.OwnerID).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_USER_NOT_EXIST.String())
	}

	return storage.MySqlDb().Create(item).Error
}

func (service *WprItem) FindByParentID(parentID uint) (int64, []*model.WprItem, error) {
	var (
		err    error
		total  int64
		result = make([]*model.WprItem, 0)
	)

	if err = storage.MySqlDb().
		Model(&model.WprItem{}).
		Where("parent_id = ?", parentID).
		Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().
		Model(&model.WprItem{}).
		Where("parent_id = ?", parentID).
		Preload("Project").
		Preload("OwnerUser").
		Preload("FinisherUser").
		Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}

func (service *WprItem) FindList() (int64, []*model.WprItem, error) {
	var (
		err    error
		total  int64
		result = make([]*model.WprItem, 0)
	)

	if err = storage.MySqlDb().Model(&model.WprItem{}).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Model(&model.WprItem{}).
		Preload("Project").
		Preload("OwnerUser").
		Preload("FinisherUser").
		Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}

func (service *WprItem) Delete(ids []int64) error {
	var (
		err error
		tx = storage.MySqlDb().Begin()
	)
	if err = tx.Delete(model.WprItem{}, "id in (?)", ids).Error; err != nil {
		goto ERR
	}
	tx.Commit()
	return nil
ERR:
	tx.Rollback()
	return err
}

func (service *WprItem) UpdateOne(item *model.WprItem) error {
	return storage.MySqlDb().Model(&model.WprItem{}).Save(&item).Error
}
